<template>
  <div class="specSet">
    <!-- 规格类型区域 -->
    <div class="specType">
      <div class="typeTop jscenter">
        <p>选择规格类型</p>
        <p class="green" @click="goToSpecManage">管理</p>
      </div>
      <div class="typeCenter">
        <div
          class="typeItem ccenter"
          v-for="item in receptDataMap.specList"
          :key="item.id"
          @click="addNewType(item)"
        >
          {{ item.name }}
        </div>
      </div>
    </div>

    <!-- 规格卡片区域 -->
    <section class="specCard">
      <div class="spectCardItem" v-for="(spec, index) in receptData.specList" :key="index">
        <specCard
          :options="spec"
          @add="addSpec(spec)"
          @delete="deleteSpec(spec)"
          @edit="editSpec(spec)"
          @delete-child="deleteSpecChild"
        ></specCard>
      </div>
    </section>

    <div class="typeBottom" @click="addnewCard">+添加新规格</div>

    <!-- 规格详细区域 -->
    <section v-if="receptData.specList.length > 0">
      <div class="specdetail">
        <div class="detailTop jscenter">
          <p>详细规格</p>
          <p class="green" @click="openGroupSet">批量设置</p>
        </div>
        <div class="detailSpecs acenter">
          <div class="specItem" v-for="(spec, index) in receptData.specList">
            <span v-if="index !== 0">/</span>{{ spec.name }}
          </div>
        </div>
        <div class="detailContent">
          <div class="detailItem" v-for="(detailItem, index) in formData">
            <p class="detailItemName">{{ detailItem.name }}</p>
            <div class="columns">
              <div class="column">
                <p>价格<span>*</span></p>
                <input
                  type="text"
                  v-model="detailItem.price"
                  @keyup="detailItem.price = unsignFloat(detailItem.price)"
                  @blur="detailItem.price = unsignFloat(detailItem.price)"
                />
              </div>
              <div class="column">
                <p>成本价</p>
                <input
                  type="text"
                  v-model="detailItem.basePrice"
                  @keyup="detailItem.basePrice = unsignFloat(detailItem.basePrice)"
                  @blur="detailItem.basePrice = unsignFloat(detailItem.basePrice)"
                />
              </div>
              <div class="column">
                <p>库存</p>
                <input
                  type="number"
                  v-model="detailItem.stok"
                  onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
                  placeholder="为空则库存无限"
                />
              </div>
              <div class="column" @click.stop="handleClickColumnImg(index)">
                <p>图片</p>

                <nut-uploader url="#" accept="image/*" :before-upload="beforeUpload">
                  <img
                    v-if="detailItem.img"
                    class="camera uploadimg"
                    :src="commonStore.img_domain + detailItem.img"
                  />
                  <img
                    v-else
                    class="camera"
                    src="@/assets/addstart/introduce/introduce_camera.png"
                  />
                </nut-uploader>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 底部保存按钮 -->
    <div class="bottom">
      <div class="action">
        <button class="action-btn" @click="handleSave">保存设置</button>
      </div>
      <i v-if="isIOS" class="toolman"></i>
    </div>

    <!-- 弹窗 -->
    <myDialog ref="editSpecNameRef" @confirm="changeSpecName" @cancel="cancelChangeSpecName">
      <template #title>
        <p class="dialogTitle">修改规格名称</p>
      </template>
      <div class="dialogCenter jscenter">
        <p>规格名称</p>
        <input type="text" placeholder="请输入规格名称" v-model="tempModel" />
      </div>
      <template #confirm> 保存 </template>
    </myDialog>

    <myDialog ref="addSpecTypeRef" @confirm="addSpecType" @cancel="cancelSpecType">
      <template #title>
        <p class="dialogTitle">添加具体规格</p>
      </template>
      <div class="dialogCenter jscenter">
        <p>具体规格名称</p>
        <input type="text" placeholder="请输入具体规格名称" v-model="tempModel" />
      </div>
      <template #confirm> 保存 </template>
    </myDialog>

    <myDialog ref="groupSetRef" @confirm="modifyMulti" @cancel="cancelSpecType">
      <template #title>
        <p class="dialogTitle">批量设置</p>
      </template>
      <div class="dialogBody">
        <div class="centerItem jscenter">
          <p>价格<span>*</span>(¥)</p>
          <input
            type="text"
            placeholder="请输入价格"
            v-model="tempSpec.price"
            @keyup="tempSpec.price = unsignFloat(tempSpec.price)"
            @blur="tempSpec.price = unsignFloat(tempSpec.price)"
          />
        </div>
        <div class="centerItem jscenter">
          <p>成本价(¥)</p>
          <input
            type="text"
            placeholder="请输入成本价"
            v-model="tempSpec.basePrice"
            @keyup="tempSpec.basePrice = unsignFloat(tempSpec.basePrice)"
            @blur="tempSpec.basePrice = unsignFloat(tempSpec.basePrice)"
          />
        </div>
        <div class="centerItem jscenter">
          <p>库存</p>
          <input type="text" placeholder="为空则库存无限" v-model="tempSpec.stok" />
        </div>
      </div>
      <template #confirm> 保存 </template>
    </myDialog>
  </div>
</template>

<script setup lang="ts">
  import { onActivated, ref, nextTick } from "vue"
  import specCard from "./components/specCard.vue"
  import myDialog from "@/components/Dialog/index.vue"
  import { useRoute, useRouter } from "vue-router"
  import { nanoid } from "nanoid"
  import _ from "lodash"
  import { judgeClient } from "@/utils/utils"
  import { Toast } from "@nutui/nutui"
  import { watch } from "vue"
  import { getSpecListApi, uploadImgApi, getOSTokenApi } from "@/api/addstart/index"
  import { getClient, ossPath } from "@/utils/alioss"
  import useCommonStore from "@/store/common"
  import { unsignFloat } from "@/utils/pub-use"
  const { isIOS } = judgeClient()

  // ------- store
  const commonStore = useCommonStore()
  const currentUploadItemIndex = ref<number>(0)
  const route = useRoute()
  let tempModel = ref<any>()
  const formData = ref<any[]>([])
  const receptDataMap = ref<any>({
    specList: []
  })
  const receptData = ref<any>({
    specList: []
  })
  const credentials = ref<any>({
    securityToken: "",
    accessKeySecret: "",
    accessKeyId: ""
  })

  watch(
    () => receptData.value,
    () => {
      let source: any = []
      let tempArray: any = []
      let arrayResults: any = []
      receptData.value.specList.map((father: any, index: number) => {
        if (father.specs.length) {
          source.push(father.specs)
        }
      })
      combine(source)
      function combine(array: any, index: number = 0) {
        if (array.length) {
          array[index].forEach((item: any) => {
            tempArray[index] = item
            if (index + 1 < array.length) {
              combine(array, index + 1)
            } else {
              let name = ""
              let tempId = ""
              tempArray.map((element: any, location: number) => {
                name = name + "/" + element.spec_value
                tempId = tempId + "," + element.spec_id
              })
              name = name.substring(1)
              tempId = tempId.substring(1)
              tempId = tempId
                .split(",")
                .sort((a: any, b: any) => a * 1 - b * 1)
                .join(",") // 排序

              let final = {
                id: tempId,
                price: "",
                basePrice: "",
                stok: undefined,
                img: "",
                name: name
              }

              arrayResults.push(final)
            }
          })
        }
      }
      formData.value = arrayResults
    },
    { deep: true }
  )

  //---------------------------------------添加新规格---------------------------------------
  const router = useRouter()
  const addnewCard = () => {
    router.push({
      path: "/spec/addNewSpecCard",
      query: {
        id: route.query.id
      }
    })
  }

  const deleteSpec = (item: any) => {
    receptData.value.specList.map((spec: any, index: number) => {
      if (spec.nId == item.nId) {
        receptData.value.specList.splice(index, 1)
      }
    })
  }
  const addNewType = (item: any) => {
    if (receptData.value.specList.length >= 2) {
      Toast.text("最多支持选择两种规格类型")
      return
    }

    const payload = _.cloneDeep(item)
    payload.specs.map((it: any) => (it.nId = nanoid()))

    receptData.value.specList.push({ ...payload, nId: nanoid() })
  }

  //---------------------------------------删除规格子类---------------------------------------
  const deleteSpecChild = (card: any, type: any) => {
    receptData.value.specList.map((item: any) => {
      if (card.nId == item.nId) {
        item.specs.map((element: any, location: number) => {
          if (element.nId == type.nId) {
            item.specs.splice(location, 1)
          }
        })
      }
    })
  }
  //---------------------------------------规格管理页面---------------------------------------
  const goToSpecManage = () => {
    router.push({
      path: "/spec/specManage",
      query: {
        id: route.query.id
      }
    })
  }
  //--------------------------------------------修改规格名称弹窗--------------------------------------------
  let tempEdit: any = ref({
    name: ""
  })
  const editSpecNameRef = ref<InstanceType<typeof myDialog>>()
  const editSpec = (item: any) => {
    tempEdit.value = _.cloneDeep(item)
    editSpecNameRefDialog(item)
  }
  const editSpecNameRefDialog = (item: any) => {
    editSpecNameRef.value?.openDialog()
  }

  const changeSpecName = () => {
    receptData.value.specList.map((item: any, index: number) => {
      if (item.nId == tempEdit.value.nId) {
        item.name = tempModel.value
        item.specs.map((i: any) => (i.spec_name = tempModel.value))
        tempModel.value = ""
      }
    })
  }
  const cancelChangeSpecName = () => {
    tempSpec.value.name = ""
    tempModel.value = ""
  }

  //--------------------------------------------添加具体规格名称弹窗--------------------------------------------
  const addSpecTypeRef = ref<InstanceType<typeof myDialog>>()
  const addSpec = (item: any) => {
    addSpecTypeRefDialog(item)
  }
  let tempSpec: any = ref({
    name: ""
  })
  const addSpecTypeRefDialog = (item: any) => {
    tempSpec.value = _.cloneDeep(item)
    addSpecTypeRef.value?.openDialog()
  }
  const addSpecType = () => {
    receptData.value.specList.map((item: any, index: number) => {
      if (item.nId == tempSpec.value.nId) {
        item.specs.push({
          nId: nanoid(),
          spec_name: item.name,
          spec_value: tempModel.value
        })
        tempModel.value = ""
      }
    })
  }
  const cancelSpecType = () => {
    tempSpec.value.name = ""
    tempModel.value = ""
  }
  //--------------------------------------------批量设置弹窗--------------------------------------------
  const groupSetRef = ref<InstanceType<typeof myDialog>>()
  const openGroupSet = () => {
    groupSetRefDialog()
  }
  const groupSetRefDialog = () => {
    groupSetRef.value?.openDialog()
  }
  const modifyMulti = () => {
    formData.value.map((item: any) => {
      item.price = tempSpec.value.price
      item.basePrice = tempSpec.value.basePrice
      item.stok = tempSpec.value.stok
    })
  }

  //--------------------------------------------上传图片--------------------------------------------
  const handleClickColumnImg = (index: number) => {
    currentUploadItemIndex.value = index
  }
  const beforeUpload = (fileList: File[]) => {
    // uploadImg(fileList[0])
    uploadOSS(fileList[0], "image")

    return new Promise((resolve) => {
      resolve(fileList)
    })
  }

  //--------------------------------------------保存设置--------------------------------------------
  const handleSave = () => {
    if (!receptData.value.specList || receptData.value.specList.length <= 0) {
      Toast.warn("请选择类型")
    } else {
      let flag = true
      for (const item of formData.value) {
        if (!item.price) {
          flag = false
          break
        }
      }

      if (!flag) {
        Toast.warn("请填写价格")
        return
      }
      window.localStorage.setItem(
        `specData1-${route.query.id}`,
        JSON.stringify(receptData.value.specList)
      )
      window.localStorage.setItem(`specData2-${route.query.id}`, JSON.stringify(formData.value))
      receptData.value.specList = []
      formData.value = []
      const nowAddType = window.localStorage.getItem("nowAddType")
      if (nowAddType && nowAddType == "ordinary") {
        router.push("/ordinary")
      } else {
        router.push("/community")
      }
      // router.back()
    }
  }

  //--------------------------------------------网络请求--------------------------------------------
  async function getSpecList() {
    const res = await getSpecListApi()
    const { system_specs = [], custom_specs = [] } = res.result

    const s_specs = _.cloneDeep(system_specs)
    const c_specs = _.cloneDeep(custom_specs)

    s_specs.map((item: any) => {
      item.isDefault = true
    })

    const payload = [...s_specs, ...c_specs]
    payload.map((item: any) => {
      item.nId = nanoid()

      item.specs.map((it: any) => {
        it.nId = nanoid()
      })
    })

    receptDataMap.value.specList = [...payload]
  }
  async function uploadImg(imgfile: File) {
    const res = await uploadImgApi({ imgfile })
    if (res.code == 0) {
      const { img_key } = res.result
      formData.value[currentUploadItemIndex.value].img = img_key
    }
  }
  // 接口：获取OSS Token
  async function getOSSToken() {
    const res = await getOSTokenApi()
    if (res.code == 0) {
      const { accessKeyId, accessKeySecret, securityToken } = res.result.credentials
      credentials.value.accessKeyId = accessKeyId
      credentials.value.accessKeySecret = accessKeySecret
      credentials.value.securityToken = securityToken
    }
  }
  async function uploadOSS(file: any, fileType: any) {
    var imgUrl = ossPath(file, fileType)
    getClient(
      credentials.value.accessKeyId,
      credentials.value.accessKeySecret,
      credentials.value.securityToken
    )
      .multipartUpload(imgUrl, file)
      .then((res: any) => {
        if (res.res.statusCode == 200) {
          var pathurl = res.name.replace("image/", "")
          formData.value[currentUploadItemIndex.value].img = pathurl
        }
      })
  }

  //--------------------------------------------生命周期函数--------------------------------------------
  function setupInit() {
    getSpecList()
    getOSSToken()
  }
  setupInit()

  onActivated(() => {
    getSpecList()

    const localSpecData1 = window.localStorage.getItem(`specData1-${route.query.id}`)
    const localSpecData2 = window.localStorage.getItem(`specData2-${route.query.id}`)
    if (localSpecData1 && localSpecData2) {
      receptData.value.specList = JSON.parse(localSpecData1)
      nextTick(() => {
        formData.value = JSON.parse(localSpecData2)
      })
    } else {
      receptData.value.specList = []
      formData.value = []
    }
  })
</script>

<style lang="scss" scoped>
  .specSet {
    height: 100vh;
    overflow: auto;
    background: #f8f9fa;

    .dialogTitle {
      font-weight: 500;
      color: #000000;
      font-size: 36px;
      margin-top: 36px;
    }
    .dialogCenter {
      padding-bottom: 30px;
      margin: 59px 30px 63px 50px;
      border-bottom: 1px solid #eeeeee;
      p {
        color: #000000;
        font-size: 30px;
        word-break: keep-all;
      }
    }
    .dialogBody {
      padding-bottom: 30px;
      margin: 30px 30px 63px 50px;
      p {
        color: #000000;
        font-size: 30px;
        word-break: keep-all;
        span {
          color: #f55726;
        }
      }
      .centerItem {
        padding: 30px 0;
        border-bottom: 1px solid #eee;
        input {
          margin-right: 0;
        }
      }
    }
    input {
      margin-left: 44px;
      margin-right: auto;
      width: 308px;
      height: 42px;
      line-height: 42px;
      background: none;
      outline: none;
      border: none;
      color: #000000;
      font-size: 28px;
    }

    section {
      margin-top: 20px;
      padding: 0 30px;
    }
    .specType {
      margin-top: 30px;
      background: #ffffff;
      padding: 30px;
      .typeTop {
        border-bottom: 1px solid #eeeeee;
        padding-bottom: 23px;
        p {
          font-weight: 500;
          color: #000000;
          font-size: 32px;
        }
        .green {
          color: #40ae36;
          font-weight: 400;
          font-size: 28px;
        }
      }
      .typeCenter {
        display: flex;
        flex-wrap: wrap;
        .typeItem {
          margin-top: 15px;
          width: 136px;
          height: 65px;
          border-radius: 33px;
          border: 1px solid #999999;
          font-size: 26px;
          color: #000000;
          margin-right: 20px;
        }
      }
    }

    .specCard {
      .spectCardItem {
        margin-top: 20px;
      }
    }

    .typeBottom {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 630px;
      height: 90px;
      background: #ffffff;
      border-radius: 16px;
      border: 1px solid #40ae36;
      font-size: 28px;
      font-family: PingFang-SC-Regular, PingFang-SC;
      font-weight: 400;
      color: #40ae36;
      margin: 20px auto;
    }

    .specdetail {
      background: #ffffff;
      border-radius: 20px;
      padding: 20px;
      margin-bottom: 220px;

      .detailTop {
        p {
          font-weight: 500;
          color: #000000;
          font-size: 30px;
        }
        .green {
          color: #40ae36;
          font-size: 28px;
        }
      }
      .detailSpecs {
        flex-wrap: wrap;
        margin-top: 22px;
        color: #000000;
        font-size: 28px;
        line-height: 40px;
        padding-bottom: 15px;
        border-bottom: 1px solid #eee;
      }
      .detailContent {
        .detailItem {
          margin-top: 20px;
          .detailItemName {
            color: #000000;
            font-size: 26px;
          }
          .columns {
            margin-top: 8px;
            display: flex;
            justify-content: space-between;
            .column {
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              p {
                color: #999999;
                font-size: 24px;
                span {
                  color: #f55726;
                }
              }
              input {
                width: 185px;
                height: 64px;
                border-radius: 6px;
                border: 2px solid #eeeeee;
                margin: 0;
                font-size: 26px;
                margin-top: 10px;
              }
              .camera {
                right: 56px;
                width: 64px;
                transform: translateY(-2px);
              }
              .camera.uploadimg {
                display: block;
                height: 100%;
                width: 64px;
                height: 64px;
              }
            }
            .column:nth-of-type(1),
            .column:nth-of-type(2) {
              width: 164px;

              input {
                width: 164px;
              }
            }
          }
        }
      }
    }

    .bottom {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;

      .action {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 112px;
        background: #ffffff;

        .action-btn {
          display: flex;
          justify-content: center;
          align-items: center;
          border: none;
          width: 630px;
          height: 90px;
          background: linear-gradient(90deg, #3ebd33 0%, #9fdf4f 100%);
          box-shadow: 0px 10px 20px 0px rgba(105, 194, 97, 0.27);
          border-radius: 45px;
          font-size: 30px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #ffffff;
        }
      }

      .toolman {
        display: block;
        width: 100%;
        height: 68px;
        background: #ffffff;
      }
    }

    :deep(.nut-uploader__slot) {
      width: 100%;
      display: flex;
      flex-direction: column;
    }
    :deep(.nut-uploader__preview) {
      display: none;
    }
  }
</style>
